package com.fms.data.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.fms.model.domain.FlowSheet;

public class FlowSheetOperations implements IFlowSheetOperations
{
	
	
	private String	templateFile;

	public FlowSheetOperations(String _templateFile)
	{
		templateFile = _templateFile;
	}
	
	public FlowSheetOperations()
	{
		this("template/blank.xls");
	}
	
	
	public void createTemplate(FlowSheet sheet) throws FileException
	{
		File f = new File(sheet.getFileName());
		if(f.exists())
		{
			throw new FileException("The file " + f.getName() + " already exists in that location.");
		}

		File template = new File(templateFile);
		if(!template.exists())
		{
			throw new FileException("The template, " + template.getName() + " does not exist!");
		}
		
		try
		{
			copy(template, f);			
		}
		catch(Exception e)
		{
			throw new FileException(e.getMessage());
		}
		
		if(sheet.getDate() != null)
		{
			try
			{
				HSSFWorkbook book = new HSSFWorkbook(new FileInputStream(sheet.getFileName()));
				HSSFSheet worksheet = book.getSheet("Sheet1");
				if(worksheet == null)
				{
					throw new Exception("Unable to open worksheet.");
				}
				
				
				
				SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");				
				setCell(4, 0, "  Date: " + format.format(sheet.getDate().getTime()), worksheet);	

				SimpleDateFormat timeFormat = new SimpleDateFormat("h:mma");
				
				for(int i = 0; i < 5; i++)
				{
					setCell(21 + i, 0, timeFormat.format(sheet.getReadingTime(i).getTime()), worksheet);							
				}
				
				

				Calendar startTime = sheet.getDate();
				Calendar endTime = sheet.getEndTime();
				

				setCell(2, 8, "  Start Time: " + timeFormat.format(startTime.getTime()), worksheet);	
				setCell(3, 8, "  Stop Time: " + timeFormat.format(endTime.getTime()), worksheet);	
				
				SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EEEE");
				
				setCell(4, 5, "Day of the Week: " + dayOfWeekFormat.format(startTime.getTime()), worksheet);
				
				FileOutputStream out = new FileOutputStream(sheet.getFileName());
				book.write(out);
				out.close();
			} 
			catch (Exception e)
			{
				throw new FileException(e.getMessage());
			} 
		}		
	}
	
	private void setCell(int row, int column, String text, HSSFSheet worksheet) throws Exception
	{
		HSSFRow currentRow = worksheet.getRow(row);
		if(currentRow == null)
		{
			throw new Exception("Unable to fetch date row.");
		}
		HSSFCell cell = currentRow.getCell(column);
		if(cell == null)
		{
			throw new Exception("Unable to fetech date cell");
		}
		
		cell.setCellValue(new HSSFRichTextString(text));
	}
	
	
	
    // Copies src file to dst file.
    // If the dst file does not exist, it is created
    private void copy(File src, File dst) throws IOException 
    {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
    
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) 
        {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }


	public boolean exists(FlowSheet flowSheet)
	{
		return new File(flowSheet.getFileName()).exists();
	}

	public void delete(String with)
	{
		new File(with).delete();
		
	}


	
}
